<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/11 0011
 * Time: 19:46
 */

class socket_server
{
    protected $socket_server = null;
    private $address = null;

    public $connect;
    public $onMessage;

    public function __construct($socket_address)
    {
        $this->address = $socket_address;
    }

    public function listen()
    {
        $context = stream_context_create([
            'socket' => [
                'backlog' => 102400
            ]
        ]);
        stream_context_set_option($context, 'socket', 'so_reuseport', 1); //请求负载均衡分配到不同的进程
        stream_context_set_option($context, 'socket', 'so_reuseaddr', 1);
        $this->socket_server = stream_socket_server($this->address, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context);
        swoole_event_add($this->socket_server, function ($fd) {
            $clientSocket = stream_socket_accept($fd);
            //出发连接事件回调
            if ($clientSocket && is_callable($this->connect)) {
                call_user_func_array($this->connect, array($fd, '触发连接'));
            }
            //监听客户端可读
            swoole_event_add($clientSocket, function ($fp) {
                $data = fread($fp, 8192);
                if ((feof($fp) || !is_resource($fp))) {
                    swoole_event_del($fp); //删除事件
                    fclose($fp);
                    return null;
                } else {
                    //表示一个正常的连接，已经读取到消息，交给回掉函数处理
                    if (!empty($data) && ($this->onMessage instanceof \Closure)) {
//                        var_dump('触发消息回调');
                        call_user_func_array($this->onMessage, array($fp, $data));
                    }
                }

            });
        });

    }

}